﻿using IBatisNet.DataMapper;
using IBatisNet.DataMapper.MappedStatements;
using IBatisNet.DataMapper.Scope;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ERP.DAL
{
    public abstract class DalBase
    {
        public static GetSqlMapper objMapper = new GetSqlMapper();

        /// <summary>
        /// 获取数据库连接字符串
        /// </summary>
        /// <returns></returns>
        public string GetConnectionString()
        {
            return objMapper.GetMapper().DataSource.ConnectionString;
        }
        
        public static string GetSQL(string _strTag, object _objParam)
        {
            return objMapper.GetSql(_strTag, _objParam, null);
        }

        #region Properties

        public static ISqlMapper sqlMapper = objMapper.GetMapper();

        #endregion
        
        #region Functions

        /// <summary>  
        /// 得到运行时ibatis.net动态生成的SQL  
        /// </summary>   
        /// <param name="statementName"></param>  
        /// <param name="paramObject"></param>  
        /// <returns></returns>  
        public static string GetRuntimeSql(string statementName, object paramObject)
        {
            string result = string.Empty;
            try
            {
                IMappedStatement statement = sqlMapper.GetMappedStatement(statementName);
                if (!sqlMapper.IsSessionStarted)
                {
                    sqlMapper.OpenConnection();
                }
                RequestScope scope = statement.Statement.Sql.GetRequestScope(statement, paramObject, sqlMapper.LocalSession);
                result = scope.PreparedStatement.PreparedSql;
            }
            catch (Exception ex)
            {
                result = "获取SQL语句出现异常:" + ex.Message;
            }
            return result;
        }

        #endregion

        #region 事务处理
        /// <summary>
        /// 启动事务
        /// </summary>
        public static void IBeginTransaction()
        {
            objMapper.GetMapper().BeginTransaction();//启动事务
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public static void ICommitTransaction()
        {
            objMapper.GetMapper().CommitTransaction();//提交事务
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        public static void IRollBackTransaction()
        {
            objMapper.GetMapper().RollBackTransaction();//回滚事务
        }
        #endregion
        
    }
}
